package cn.bonoon.controllers.user;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.bonoon.kernel.security.LogonUser;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.controllers.AbstractController;

@Controller
@RequestMapping("s/user")
public class UserInfoController extends AbstractController {
	private final Map<String, UserCenterAppender> centers;
	private String tabInfo;
	@Value("${user.password.pattern}")
	private String pattern;
	@Value("${user.password.pattern.exception}")
	private String patternException;

	public UserInfoController() {
		centers = new HashMap<String, UserCenterAppender>();
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		super.afterPropertiesSet();
		StringBuilder sb = new StringBuilder();
		Map<String, UserCenterAppender> appenders = applicationContext.getBeansOfType(UserCenterAppender.class);
		if (null != appenders && !appenders.isEmpty()) {
			String baseurl = toUrl("/u/user/");
			for (UserCenterAppender uca : appenders.values()) {
				sb.append("<div href='").append(baseurl).append(uca.getKey()).append("!info' title='").append(uca.getName());
				if (StringHelper.isNotEmpty(uca.getIconCls())) {
					sb.append("' data-settings=\"iconClassname:'").append(uca.getIconCls());
				}
				sb.append("'\"></div>");

				centers.put(uca.getKey(), uca);
			}
		}
		tabInfo = sb.toString();
	}

	@RequestMapping("info/!{key}/index.do")
	public String get(Model model, @PathVariable("key") String key) {
		LogonUser user = getUser();
		model.addAttribute("name", user.getDisplayName() + "(" + user.getUsername() + ")");
		model.addAttribute("userInfoTabs", tabInfo);
		model.addAttribute("pattern", pattern);
		model.addAttribute("patternException", patternException);
		return "user/user-info";
	}

	@RequestMapping("{key}!info")
	public String info(Model model, @PathVariable("key") String key) {
		model.addAttribute("userInfoTabs", tabInfo);
		model.addAttribute("pattern", pattern);
		model.addAttribute("patternException", patternException);
		return "user/user-info-append";
	}
}
